from time import sleep

import pytest
import requests

from api import log
from api.api_register_login import ApiRegisterLogin  # 导入封装的注册登录API类
from tools import com_assert, read_json


class TestRegisterLogin:
    """测试用户注册登录流程的测试类"""

    def setup(self):
        """每个测试方法执行前的准备工作"""
        self.session = requests.session()  # 创建会话对象，用于保持多个请求间的状态

        log.info("正在获取session对象：{}".format(self.session))

        self.api = ApiRegisterLogin(self.session)  # 初始化API对象

        log.info("正在获取ApiRegisterLogin对象：{}".format(self.api))

    def teardown(self):
        """每个测试方法执行后的清理工作"""
        self.session.close()  # 关闭会话，释放资源

        log.info("关闭session对象：{}".format(self.session))

    @pytest.mark.parametrize("random,expect_code",read_json("register_login.json","img_code"),)
    def test01_img_code(self, random,expect_code):
        """
        测试获取图片验证码功能

        :param random: 随机数参数，用于防止图片缓存
        """
        try:
            # 调用获取图片验证码API
            result = self.api.api_img_code(random)
            log.info("图片验证码接口测试结果为: {}".format(result.status_code))
            com_assert(result, expect_code=expect_code)
            log.info("图片验证接口断言通过")
        except Exception  as e :
            log.error(e)
            raise

    @pytest.mark.parametrize("phone,imgVeifityCode,expect_json", read_json("register_login.json", "iphone_code"))
    def test02_iphone_code(self, phone,imgVeifityCode,expect_json):
        """
        测试获取短信验证码功能

        :param phone: 测试用手机号码
        :param imgVeifityCode: 图片验证码
        """
        try:
            # 先获取图片验证码（模拟正常业务流程）
            self.api.api_img_code(123456)
            # 调用获取短信验证码API
            result = self.api.api_phone_code(phone, imgVeifityCode)
            log.info("短信验证码接口测试结果为: {}".format(result.text))
            com_assert(result, expect_json=expect_json)
            log.info("短信验证接口断言通过")

        except Exception  as e :
            log.error(e)
            raise

    @pytest.mark.parametrize("phone,verifycode,password,phonecode,expect_json", read_json("register_login.json", "register"))
    def test03_register(self, phone,verifycode,password,phonecode,expect_json):
        """
        测试用户注册功能

        :param phone: 注册手机号
        :param imgVeifityCode: 图片验证码
        :param password: 用户密码
        :param phonecode: 短信验证码
        """
        try:
            # 先获取图片验证码（模拟正常业务流程）
            self.api.api_img_code(123456)
            # 调用获取短信验证码API（注册所需）
            self.api.api_phone_code(13000000001, 8888)
            # 调用用户注册API
            result = self.api.api_register(phone, verifycode, password, phonecode)
            log.info("注册接口测试结果为: {}".format(result.text))
            com_assert(result,  expect_json=expect_json)
            log.info("注册接口断言通过")
        except Exception  as e :
            log.error(e)
            raise

    @pytest.mark.parametrize("keywords,password,expect_json",read_json("register_login.json", "login"))
    def test04_login(self, keywords,password,expect_json):
        """
        测试用户登录功能
        :param keyword: 登录标识（可以是用户名、手机号等）
        :param password: 用户密码
        """
        try:
            i = 1
            result = None
            if password == "error123":
                while i <= 3:
                    result = self.api.api_login(keywords, password)
                    i += 1
                assert "锁定" in result.text
                log.info("登录——锁定接口断言通过")
                sleep(60)
                # 登录成功->判断解锁
                result = self.api.api_login("13600001111", "test123")
                log.info("登录接口测试结果为: {}".format(result.text))
                com_assert(result, expect_json=expect_json)
                log.info("登录接口断言通过")
            else:
                result = self.api.api_login(keywords, password)
                log.info("登录接口测试结果为: {}".format(result.text))
                com_assert(result, expect_json=expect_json)
                log.info("登录接口断言通过")
        except Exception as e:
            # 捕获异常的目的就是记录错误日志
            log.error(e)
            # 抛异常
            raise

        # try:
        #     # 调用登录API
        #     result = self.api.api_login(keyword, password)
        #     com_assert(result, expect_json=expect_json)
        # except Exception  as e :
        #     print("错误",e)
        #     raise

    @pytest.mark.parametrize("status,expect_json",read_json("register_login.json", "login_status"))
    def test05_login_status(self, status,expect_json):
        """
        测试用户登录状态检查功能

        :param status: 当前登录状态，用于控制测试前置条件
        """
        # 根据传入的状态参数决定是否执行登录
        try:
            if status == "登录":
                # 如果状态为"登录"，则先执行登录操作
                self.api.api_login(13000000001, 123456)
            # 调用登录状态检查API
            result = self.api.api_login_status()
            log.info("登录状态接口测试结果为: {}".format(result.text))
            com_assert(result, expect_json=expect_json)
            log.info("登录状态接口断言通过")
        except Exception as e:
            log.error(e)
            raise